package com.h2cloud.JUCTest.cas;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class UnsafeAccessor {
    private static final Unsafe unsafe;

    static {
        try {
            // theUnsafe 字段是 Unsafe 类的一个静态字段，
            // 在通过反射获取它时，传入 null 表示不需要通过对象实例来访问该字段，而是直接通过类来访问静态字段。
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            unsafe = (Unsafe) theUnsafe.get(null);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new Error(e);
        }
    }

    public static Unsafe getUnsafe() {
        return unsafe;
    }
}
